package top.hjcwzx.wrench.mqtt.service.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import top.hjcwzx.wrench.mqtt.annotation.MqttSubscribe;
import top.hjcwzx.wrench.mqtt.config.MqttConfigProperties;
import top.hjcwzx.wrench.mqtt.enums.MessageHandlerStrategyEnum;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.Map;

/**
 *
 * <p><b>类名：</b> MqttSubscribeRegistrar</p>
 * <p><b>描述：</b> mqtt连接以及订阅注册器</p>
 * <p><b>创建时间：</b> 2025-06-17 15:34</p>
 *
 * @author 胡锦程
 */
public class MqttSubscribeRegistrar {

    private Logger log = LoggerFactory.getLogger(MqttSubscribeRegistrar.class);
    private final MqttService mqttService;


    public MqttSubscribeRegistrar(MqttService mqttService) {
        this.mqttService = mqttService;
    }

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private MqttConfigProperties mqttConfigProperties;

    @PostConstruct
    public void registerMqttSubscribers() {
        if (
                MessageHandlerStrategyEnum.ANNOTATION_CALLBACK.equals(mqttConfigProperties.getStrategyEnum()) ||
                MessageHandlerStrategyEnum.MIXED.equals(mqttConfigProperties.getStrategyEnum())) {
            //仅注解式策略有效时执行
            Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Component.class);
            for (Object bean : beans.values()) {
                for (Method method : bean.getClass().getDeclaredMethods()) {
                    MqttSubscribe mqttSubscribe = method.getAnnotation(MqttSubscribe.class);
                    if (mqttSubscribe != null) {
                        String topic = mqttSubscribe.topic();
                        Class<?> type = mqttSubscribe.messageType();
                        Method targetMethod = method;

                        mqttService.registerHandler(topic, type, payload -> {
                            try {
                                targetMethod.invoke(bean, payload);
                            } catch (Exception e) {
                                log.error("🔥 注解式 MQTT方法调用失败: {}", e.getMessage(), e);
                            }
                        });

                        log.info("📌 注解式 注册MQTT监听：topic={" + topic + "} -> " + bean.getClass().getSimpleName() + "." + method.getName());
                    }
                }
            }
        }

        try {
            mqttService.connect();
        } catch (Exception e) {
            log.warn("MQTT 连接异常: {}", e);
        }
        mqttService.subscribeDefaultTopics();
        mqttService.subscribeHandlers();
    }

}
